package com.guigu.servicegoods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.IdWorker.IdWorker;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.*;
import com.guigu.servicegoods.mapper.TbSpuMapper;
import com.guigu.servicegoods.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbSpuServiceImpl extends ServiceImpl<TbSpuMapper, TbSpu> implements TbSpuService {

    @Autowired
    private TbSkuService skuService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TbCategoryService categoryService;

    @Autowired
    private TbBrandService brandService;

    @Autowired
    private TbCategoryBrandService categoryBrandService;

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbSpu> wrapper = createExample(searchMap);
        Page<TbSpu> pageSpu = new Page<>(page,size);
        baseMapper.selectPage(pageSpu,wrapper);
        return Result.ok().data("row",pageSpu.getRecords()).data("total",pageSpu.getTotal());
    }

    @Override
    public void saveGoods(Goods goods) {
        // 保存spu
        TbSpu spu = goods.getSpu();
        // 生成spu的分布式ID
        spu.setId(idWorker.nextId()+"");
        baseMapper.insert(spu);

        // 获取三级分类对象
        TbCategory category = categoryService.getById(spu.getCategory3Id());
        // 获取对应的品牌对象
        TbBrand brand = brandService.getById(spu.getBrandId());
        List<TbSku> skuList = goods.getSkuList();
        for (TbSku sku: skuList){
            // 生成sku 的分布式ID
            sku.setId(idWorker.nextId()+"");

            sku.setSn(idWorker.nextId()+"");
            // 拼接sku的name, 格式=spu的name + ' ' + 规格参数的值1 + ' ' + ....
            String name = spu.getName();
            Map<String, String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            for(String value: specMap.values()) {
                name += " " + value;
            }
            sku.setName(name);
            sku.setSpuId(spu.getId()); // 所属spuId

            sku.setCategoryId(spu.getCategory3Id()); // 三级分类编号
            sku.setCategoryName(category.getName()); // 三级分类名称
            sku.setBrandName(brand.getName()); // 所属品牌名称
            sku.setSaleNum(0); // 销量
            sku.setCommentNum(0); // 评论数
            skuService.savePriceToRedisById(sku.getId(),sku.getPrice());
            skuService.save(sku);

            // 设置品牌与分类的关联关系
            QueryWrapper<TbCategoryBrand> categoryBrandwrapper = new QueryWrapper<>();
            categoryBrandwrapper.eq("category_id",spu.getCategory3Id());
            categoryBrandwrapper.eq("brand_id",spu.getBrandId());
            int count = categoryBrandService.count(categoryBrandwrapper);
            if (count == 0){
                TbCategoryBrand categoryBrand = new TbCategoryBrand();
                categoryBrand.setCategoryId(spu.getCategory3Id());
                categoryBrand.setBrandId(spu.getBrandId());
                categoryBrandService.save(categoryBrand);
            }
        }
    }

    @Override
    public Goods findGoodsById(String id) {
        Goods goods = new Goods();
        TbSpu spu = baseMapper.selectById(id);
        goods.setSpu(spu);
        QueryWrapper<TbSku> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id",spu.getId());
        List<TbSku> skus = skuService.list(wrapper);
        goods.setSkuList(skus);
        return goods;
    }

    @Override
    public Result delete(String id) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("spu_id",id);
        List<TbSku> skuList = skuService.list(wrapper);
        for (TbSku sku : skuList){
            skuService.removeById(sku.getId());
            skuService.deletePriceFromRedis(sku.getId());
        }
        baseMapper.deleteById(id);
        return Result.ok();
    }

//    @Override
//    public Result findGoodsPage(Map<String, Object> searchMap, Integer page, Integer size) {
//        QueryWrapper<TbSpu> wrapper = createExample(searchMap);
//        Page<TbSpu> spuPage = new Page<>(page,size);
//        IPage<TbSpu> spuList = baseMapper.selectPage(spuPage, wrapper);
//        List<Goods> goodsList = new ArrayList<>();
//        for (TbSpu spu: spuList.getRecords()){
//            Goods goods = new Goods();
//            goods.setSpu(spu);
//            // 查询sku
//            QueryWrapper skuWrapper = new QueryWrapper();
//            skuWrapper.eq("spu_id",spu.getId());
//            List<TbSku> skuList = skuService.list(skuWrapper);
//            goods.setSkuList(skuList);
//            goodsList.add(goods);
//        }
//        return Result.ok().data("row",goodsList).data("total",spuList.getTotal());
//    }


    // 根据查询条件封装模块对象
    private QueryWrapper<TbSpu> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbSpu> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            // 主键
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                wrapper.like("id",searchMap.get("id"));
            }
            // 货号
            if(searchMap.get("sn")!=null && !"".equals(searchMap.get("sn"))){
                wrapper.like("sn",searchMap.get("sn"));
            }
            // SPU名
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name"))){
                wrapper.like("name",searchMap.get("name"));
            }
            // 副标题
            if(searchMap.get("caption")!=null && !"".equals(searchMap.get("caption"))){
                wrapper.like("caption",searchMap.get("caption"));
            }
            // 图片
            if(searchMap.get("image")!=null && !"".equals(searchMap.get("image"))){
                wrapper.like("image",searchMap.get("image"));
            }
            // 图片列表
            if(searchMap.get("images")!=null && !"".equals(searchMap.get("images"))){
                wrapper.like("images",searchMap.get("images"));
            }
            // 售后服务
            if(searchMap.get("saleService")!=null && !"".equals(searchMap.get("saleService"))){
                wrapper.like("sale_service",searchMap.get("saleService"));
            }
            // 介绍
            if(searchMap.get("introduction")!=null && !"".equals(searchMap.get("introduction"))){
                wrapper.like("introduction",searchMap.get("introduction"));
            }
            // 规格列表
            if(searchMap.get("specItems")!=null && !"".equals(searchMap.get("specItems"))){
                wrapper.like("spec_items",searchMap.get("specItems"));
            }
            // 参数列表
            if(searchMap.get("paraItems")!=null && !"".equals(searchMap.get("paraItems"))){
                wrapper.like("para_items",searchMap.get("paraItems"));
            }
            // 是否上架
            if(searchMap.get("isMarketable")!=null && !"".equals(searchMap.get("isMarketable"))){
                wrapper.like("is_marketable",searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if(searchMap.get("isEnableSpec")!=null && !"".equals(searchMap.get("isEnableSpec"))){
                wrapper.like("is_enable_spec",searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                wrapper.like("is_delete",searchMap.get("isDelete"));
            }
            // 审核状态
            if(searchMap.get("status")!=null && !"".equals(searchMap.get("status"))){
                wrapper.like("status",searchMap.get("status"));
            }

            // 品牌ID
            if(searchMap.get("brandId")!=null ){
                wrapper.eq("brand_id",searchMap.get("brandId"));
            }
            // 一级分类
            if(searchMap.get("category1Id")!=null ){
                wrapper.eq("category1_id",searchMap.get("category1Id"));
            }
            // 二级分类
            if(searchMap.get("category2Id")!=null ){
                wrapper.eq("category1_id",searchMap.get("category2Id"));
            }
            // 三级分类
            if(searchMap.get("category3Id")!=null ){
                wrapper.eq("category3_id",searchMap.get("category3Id"));
            }
            // 模板ID
            if(searchMap.get("templateId")!=null ){
                wrapper.eq("template_id",searchMap.get("templateId"));
            }
            // 运费模板id
            if(searchMap.get("freightId")!=null ){
                wrapper.eq("freight_id",searchMap.get("freightId"));
            }
            // 销量
            if(searchMap.get("saleNum")!=null ){
                wrapper.eq("sale_num",searchMap.get("saleNum")) ;
            }
            // 评论数
            if(searchMap.get("commentNum")!=null ){
                wrapper.eq("comment_num",searchMap.get("commentNum"));
            }
        }
        return wrapper;
    }
}
